package cn.sangyy.gift.canal.redisdel.mqlistenser;

import cn.sangyy.gift.canal.redisdel.dto.CanalSynDto;
import cn.sangyy.gift.service.impl.TenantTypeServiceImpl;
import com.alibaba.fastjson2.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "example",selectorExpression="*",consumerGroup = "service-search-consumer")
public class RedisDeleteListener implements RocketMQListener<MessageExt> {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        log.info("接收到消息：{}", msg);
        CanalSynDto canalSynDto = JSONObject.parseObject(msg, CanalSynDto.class);
        String table = canalSynDto.getTable();
        if(table.equals("t_tenant_type")){ //这里只对租户类型这张表
            String type = canalSynDto.getType();
            if(type.equals("INSERT")||type.equals("DELETE")||type.equals("UPDATE")){
                //延迟一哈
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                redisTemplate.delete(TenantTypeServiceImpl.TENANT_TYPES_CACHE_IN_REDIS);
            }
        }

    }

}